import { createRouter, createWebHistory } from 'vue-router'
import { changeI18nLocale } from '@/i18n'
import { changeTitle } from "@/common/title";
import { store } from '@/common/store'
import { UserService } from '@/common/common.object'

const IndexFrameView = () => import('@/views/index/frame.vue')
const IndexGuideView = () => import('@/views/index/guide.vue')

const ProblemListView = () => import('@/views/problem/list.vue')
const ProblemDetailView = () => import('@/views/problem/detail.vue')

const StatusListView = () => import('@/views/status/list.vue')
const StatusDetailView = () => import('@/views/status/detail.vue')

const RankListView = () => import('@/views/rank/list.vue')

const ContestFrameView = () => import('@/views/contest/frame.vue')
const ContestListView = () => import('@/views/contest/list.vue')
const ContestDetailView = () => import('@/views/contest/detail.vue')
const ContestProblemView = () => import('@/views/contest/problem.vue')
const ContestRankView = () => import('@/views/contest/rank.vue')
const ContestStatusView = () => import('@/views/contest/status.vue')

const GroupFrameView = () => import('@/views/group/frame.vue')
const GroupIndexView = () => import('@/views/group/index.vue')
const GroupListView = () => import('@/views/group/list.vue')
const GroupCreationView = () => import('@/views/group/creation.vue')
const GroupJoinedView = () => import('@/views/group/joined.vue')

const GroupDetailView = () => import('@/views/group/detail.vue')
const GroupJoinView = () => import('@/views/group/join.vue')
const GroupMembersView = () => import('@/views/group/members.vue')
const GroupNotificationsView = () => import('@/views/group/notifications.vue')
const GroupTasksView = () => import('@/views/group/tasks.vue')

const PastePublishView = () => import('@/views/paste/publish.vue')
const PasteDetailView = () => import('@/views/paste/detail.vue')

const UserProfileDetailView = () => import('@/views/user/profile/detail.vue')
const UserProfileModifyView = () => import('@/views/user/profile/modify.vue')
const UserChangePasswordView = () => import('@/views/user/password/change.vue')
const UserForgotPasswordView = () => import('@/views/user/password/forgot.vue')
const UserInfoView = () => import('@/views/user/info.vue')

const UserLoginView = () => import('@/views/user/login.vue')
const UserRegisterView = () => import('@/views/user/register.vue')


function processPageQueryParams(to, defaultPageNumber = 1, defaultPageSize = 10) {
	let params = to.query;

	if (!params.pageNumber || params.pageNumber < 0) {
		params.pageNumber = defaultPageNumber;
	}

	if (!params.pageSize || params.pageSize < 0) {
		params.pageSize = defaultPageSize;
	}
}

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: [
		{
			path: '/',
			name: 'Index',
			component: IndexFrameView,
			children: [
				{
					path: '',
					name: 'Guide',
					meta: {
						activeNav: 'index',
						titleKey: "index",
					},
					component: IndexGuideView
				},
				{
					path: '/problems',
					name: 'Problems',
					meta: {
						activeNav: 'problem',
						titleKey: "nav.problem",
					},
					component: ProblemListView,
					beforeEnter: (to, from) => {
						processPageQueryParams(to);
						return true;
					},
				},
				{
					path: '/problem/:id',
					name: 'Problem',
					meta: {
						activeNav: 'problem'
					},
					component: ProblemDetailView,
				},
				{
					path: '/status',
					name: 'Status',
					meta: {
						activeNav: 'status',
						titleKey: "nav.status",
					},
					component: StatusListView,
					beforeEnter: (to, from) => {
						processPageQueryParams(to);
						return true;
					},
				},
				{
					path: '/solution/:id',
					name: 'Solution',
					component: StatusDetailView
				},
				{
					path: '/rank',
					name: 'Rank',
					meta: {
						activeNav: 'rank',
						titleKey: "nav.rank",
					},
					component: RankListView,
					beforeEnter: (to, from) => {
						processPageQueryParams(to);
						return true;
					},
				},
				{
					path: '/groups',
					name: 'Groups',
					meta: {
						activeNav: 'group',
						titleKey: "nav.group",
					},
					component: GroupIndexView,
					children: [
						{
							path: '',
							name: 'GroupAll',
							meta: {
								activeNav: 'group',
							},
							component: GroupListView
						},
						{
							path: 'all',
							name: 'GroupList',
							meta: {
								activeNav: 'group',
							},
							component: GroupListView
						},
						{
							path: 'creation',
							name: 'GroupCreation',
							meta: {
								activeNav: 'group',
							},
							component: GroupCreationView
						},
						{
							path: 'joined',
							name: 'GroupJoined',
							meta: {
								activeNav: 'group',
							},
							component: GroupJoinedView
						},
					],
				},
				{
					path: '/contests',
					name: 'Contests',
					meta: {
						activeNav: 'contest',
						titleKey: "nav.contest",
					},
					component: ContestListView,
					beforeEnter: (to, from) => {
						processPageQueryParams(to);
						return true;
					},
				},
				{
					path: '/paste',
					name: 'Paste',
					meta: {
						activeNav: 'paste',
						titleKey: "nav.paste",
					},
					component: PastePublishView
				},
				{
					path: '/paste/:id',
					name: 'PasteDetail',
					meta: {
						// activeNav: 'paste',
						titleKey: "nav.paste",
					},
					component: PasteDetailView
				},

				{
					path: '/user/:id',
					name: 'User',
					meta: {	
						requiresAuth: true,
					},
					component: UserProfileDetailView
				},
				{
					path: '/user/:id/profile',
					name: 'UserProfile',
					meta: {	
						requiresAuth: true,
					},
					component: UserProfileDetailView
				},
				{
					path: '/user/:id/profile/modify',
					name: 'UserProfileModify',
					meta: {	
						requiresAuth: true,
					},
					component: UserProfileModifyView
				},
				{
					path: '/user/profile/modify',
					name: 'UserProfileModify',
					meta: {	
						requiresAuth: true,
					},
					component: UserProfileModifyView
				},
				{
					path: '/user/:id/info',
					name: 'UserInfo',
					component: UserInfoView
				},
				{
					path: '/user/:id/password/change',
					name: 'UserChangePassword',
					meta: {	
						requiresAuth: true,
					},
					component: UserChangePasswordView
				},
				{
					path: '/user/password/change',
					name: 'UserChangePassword',
					meta: {	
						requiresAuth: true,
					},
					component: UserChangePasswordView
				},
				/* {
					path: '/user/password/forgot',
					name: 'UserForgotPassword',
					component: UserForgotPasswordView
				}, */
			],
		},
		{
			path: '/contest/:contestId',
			component: ContestFrameView,
			children: [
				{
					path: '',
					name: 'Contest',
					component: ContestDetailView
				},
				{
					path: 'problem/:identifier',
					name: 'ContestProblem',
					component: ContestProblemView
				},
				{
					path: 'solution/:solutionId',
					name: 'ContestSolution',
					component: StatusDetailView
				},
				{
					path: 'rank',
					name: 'ContestRank',
					meta: {
						activeNav: 'rank'
					},
					component: ContestRankView
				},
				{
					path: 'status',
					name: 'ContestStatus',
					meta: {
						activeNav: 'status'
					},
					component: ContestStatusView,
					beforeEnter: (to, from) => {
						processPageQueryParams(to);
						return true;
					},
				},
			]
		},
		{
			path: '/group/:groupId',
			component: GroupFrameView,
			children: [
				{
					path: '',
					name: 'GroupDetail',
					component: GroupDetailView
				},
				{
					path: 'notifications',
					name: 'Notifications',
					meta: {
						activeNav: 'notifications'
					},
					component: GroupNotificationsView
				},
				{
					path: 'members',
					name: 'Members',
					meta: {
						activeNav: 'members'
					},
					component: GroupMembersView
				},
				{
					path: 'tasks',
					name: 'ContestTasks',
					meta: {
						activeNav: 'tasks'
					},
					component: GroupTasksView
				},
			]
		},
		{
			path: '/login',
			name: 'login',
			meta: {
				titleKey: "login",
			},
			component: UserLoginView
		},
		{
			path: '/logout',
			name: 'logout',
			beforeEnter: (to, from) => {
				UserService.logout().then(() => {
					store.onLogout();
				});
				return false;
			},
		},
		{
			path: '/forgot_password',
			meta: {
				titleKey: "forgot_password",
			},
			component: UserForgotPasswordView
		},
		{
			path: '/register',
			name: 'register',
			meta: {
				titleKey: "register",
			},
			component: UserRegisterView
		},
		{
			path: '/group/:groupId/join',
			name: 'GroupJoin',
			meta: {
				requiresAuth: true,
			},
			component: GroupJoinView
		},
	]
})

let lastCheckTime = 0;
const checkInterval = 60 * 1000;

// check login
router.beforeEach(async (to, from, next) => {
	const currentTime = new Date().getTime();

	if (currentTime - lastCheckTime > checkInterval) {
		UserService.checkLogin().then(() => {
			if (store.isVisitor()) {
				store.onLogin();
			}
		}).catch(error => {
		}).finally(() => {
			lastCheckTime = currentTime;
		});
	}

	return next()
});

// check auth
router.beforeEach(async (to, from, next) => {
	if (to.meta.requiresAuth && store.isVisitor()) {
		// todo pop require login...
		return next({
			path: '/login'
		});
	}

	return next();
});


// process i18n
router.beforeEach(async (to, from, next) => {
	let paramsLocale = to.params.locale || from.params.locale

	await changeI18nLocale(paramsLocale)

	if (to.meta.titleKey) {
		const i18nKey = to.meta.titleKey;
		const titleTemplate = `{{${i18nKey}}}`;

		changeTitle(titleTemplate);
	}

	return next()
});

// process active nav
router.beforeEach(async (to, from, next) => {
	store.activeNav = to.meta.activeNav;
	// console.log("activeNav: ", store.activeNav);

	return next()
});

export default router
